package wikisearch.testparser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;

import wikisearch.datastructures.*;

public class TestParser {
	
	private boolean start, between, end;
	public String filename = null;
	private String [] strWords = null;
	private ParserMap wordsInIdx = new ParserMap();
	private ParserMap hyperlinks = new ParserMap();
	
	public TestParser(String filename) {
		
		this.filename = new String(filename);
		
		String str = "";
		String scan;
		
		try{
			BufferedReader fileInput = new BufferedReader(new FileReader(filename));
			
			while((scan = fileInput.readLine()) != null){
				
				String regularized = scan.replaceAll("[^a-zA-Z_0-9<>/]", " "); //non alphabets are replaced before being put to scan.
				str += regularized.toLowerCase();
			}
			fileInput.close();
		} catch (IOException e){
			System.err.println("Exception while making string");
			e.printStackTrace();
		}

		strWords = str.split("\\s");
		build();
	}
	
	public String[] getString(){

		return strWords;
	}
	
	public void addToVector(){
		String[] strWords = getString();
		Vector<String> strVect = new Vector<String>();
		for(int i = 0; i < strWords.length; i++)
			strVect.add(strWords[i]);
	}

	private void build() {
		
		int fidx = -1;
		int lidx = -1;
		String linkAccum = "";
		for (int i = 0; i < this.strWords.length; i++) {
			
			String curr = strWords[i];
			if (curr.indexOf("<a>") >= 0) {
				
				fidx = i;
				curr = curr.substring(3);
				linkAccum = curr;
			}
			if (curr.indexOf("</a>") >= 0) {
				lidx = i;
				curr = curr.substring(0, curr.length() - 4);
				if (fidx < lidx) linkAccum += " " + curr;
				else linkAccum = curr;
				hyperlinks.put(linkAccum, fidx, lidx);
				fidx = -1;
				lidx = -1;
				linkAccum = "";
			}
			wordsInIdx.put(curr, i);
		}
		cleanUpArray(strWords);
	}
	
	private void cleanUpArray(String [] strWords) {
		
		for (int i = 0; i < strWords.length; i++) {
			String curr = strWords[i];
			if (curr.indexOf("<a>") >= 0) {
				curr = curr.substring(3);
			}
			if (curr.indexOf("</a>") >= 0) {
				curr = curr.substring(0, curr.length() - 4);
			}
			strWords[i] = curr;
		}
	}
	
	public ParserMap wordsInMap(){
		
		return wordsInIdx;
	}
	
	public ParserMap linksInMap(){

		return this.hyperlinks;
	}

}